package cn.aopmin.service;

import cn.aopmin.common.DataSourceContextHolder;
import cn.aopmin.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

/**
 * @author 白豆五
 * @since 2024/7/4
 */
@Service
public class UserService {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public void insertDs1(User user) {
        try {
            // todo:自定义注解+SpringAop实现数据源的切换
            DataSourceContextHolder.setDataSource("ds1");
            String sql = "insert into user(username,gender) values(?,?)";
            jdbcTemplate.update(sql,user.getUsername(), user.getGender());
        } finally {
            DataSourceContextHolder.clearDataSource();
        }
    }

    public void insertDs2(User user) {
        try {
            DataSourceContextHolder.setDataSource("ds2");
            String sql = "insert into user(username,gender) values(?,?)";
            jdbcTemplate.update(sql,user.getUsername(), user.getGender());
        } finally {
            DataSourceContextHolder.clearDataSource();
        }
    }
}